"ui";

importClass(Packages.androidx.recyclerview.widget.ItemTouchHelper);
importClass(java.util.Collections);
importClass(android.widget.PopupMenu);
var themeJs = require("./theme.js");
var settingJs = require("./setting.js");
var inAndOutJs = require("./inAndOut.js");
var rewriteWorkJs = require("./rewriteWork.js");
let addWorkJs = require("./addWork.js");
let addJs = require("./add.js");
let rewardJs = require("./reward.js");

var color = "#009688";
dialogs.setDefaultDialogType("app");

ui.layout(
    <frame id="all">
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="简单词本" bg="{{themeJs.bar}}">
                    <img id="nightMode" layout_gravity="right" src="{{themeJs.current == 'night' ? '@drawable/ic_brightness_5_black_48dp' : '@drawable/ic_brightness_2_black_48dp'}}" w="20" h="*" scaleType="fitCenter" tint="#ffffff" bg="?selectableItemBackgroundBorderless"/>
                </toolbar>
            </appbar>
            <list id="todoList" h="*" bg="{{themeJs.parent_layout}}">
                <card id="item" w="*" h="70" margin="10 5" cardCornerRadius="5dp" cardBackgroundColor="{{themeJs.layout}}" cardElevation="2dp" foreground="?selectableItemBackground">
                    <frame>
                        <horizontal gravity="center_vertical">
                            <View bg="{{this.color}}" h="*" w="5" />
                            <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                <text id="title" text="{{this.title}}" textColor="{{themeJs.text}}" textSize="16" maxLines="1" textStyle="bold"/>
                                <text id="summary" text="{{this.summary}}" textColor="{{themeJs.text2}}" textSize="14" maxLines="1" />
                            </vertical>
                        </horizontal>
                        <img id="edit" tint="{{themeJs.text}}" src="@drawable/ic_create_black_48dp" layout_gravity="right|center_vertical" w="24" h="*" marginRight="10" bg="?selectableItemBackgroundBorderless"/>
                    </frame>
                </card>
            </list>
        </vertical>
        <vertical gravity="bottom">
            <fab id="inAndOut" w="auto" h="auto" src="@drawable/ic_create_new_folder_black_48dp" margin="16" layout_gravity="bottom|right" tint="#ffffff" />
            <fab id="add" w="auto" h="auto" src="@drawable/ic_add_black_48dp" margin="16" layout_gravity="bottom|right" tint="#ffffff" />
        </vertical>
    </frame>
);

activity.setSupportActionBar(ui.toolbar);

var storage = storages.create("wordbook45qq");

//当离开本界面时保存todoList
ui.emitter.on("pause", () => {
    storage.put("items", todoList);
});

//从storage获取todo列表
var date = new Date();
var todoList = storage.get("items", []);

if (todoList.length == 0)
    addJs.addWork(todoList, "默认单词本", date.getFullYear() + "年" + date.getMonth() + "月" + date.getDate() + "日 ");

var isFirst = storage.get("isFirst", true);
if (isFirst) {
    storage.put("isFirst", false);
    ui.post(() => {
        // inAndOutJs.in45qqFromPath("./manual.45qq");
    });
}

ui.post(() => {
    ui.todoList.setDataSource(todoList);
});

ui.nightMode.on("click", (view) => {
    switch (themeJs.current) {
        case "day":
            themeJs.setTheme("night");
            view.setSource("@drawable/ic_brightness_5_black_48dp");
            break;
        case "night":
            themeJs.setTheme("day");
            view.setSource("@drawable/ic_brightness_2_black_48dp");
            break;
    }

    ui.toolbar.attr("bg", themeJs.bar);
    ui.todoList.attr("bg", themeJs.parent_layout);
    ui.todoList.getAdapter().notifyDataSetChanged();
});

ui.inAndOut.on("click", (view) => {
    threads.start(function() {
        let inAndOutDialog = dialogs.build({
            title: "选择操作",
            titleColor: themeJs.text,
            items: ["导入单词本", "导出单词本"],
            itemsColor: themeJs.text2,
            itemsSelectMode: "select",
        }).on("item_select", (index, item) => {
            switch (index) {
                case 0:
                    inAndOutJs.in45qq(todoList);
                    break;
                case 1:
                    inAndOutJs.out45qq(todoList);
                    break;
            }
        });
        inAndOutDialog.getView().attr("bg", themeJs.layout);
        inAndOutDialog.show();
    });
});

var move = {};
var start = true;
new ItemTouchHelper(new ItemTouchHelper.Callback({
    isItemViewSwipeEnabled: function() {
        return true;
    },
    getMovementFlags: function(recyclerView, viewHolder) {
        return this.makeMovementFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.LEFT);
    },
    onMove: function(recyclerView, srcHolder, targetHolder) {
        let x = srcHolder.getAdapterPosition();
        let y = targetHolder.getAdapterPosition();
        recyclerView.getAdapter().notifyItemMoved(x, y);
        if (start) {
            start = false;
            move.x = x;
            ui.todoList.getLayoutManager().findViewByPosition(x).setTranslationZ(20);
        }
        move.y = y;
        return false;
    },
    onSwiped: function(viewHolder, direction) {
        confirm("确定要删除" + todoList[viewHolder.getAdapterPosition()].title + "吗？")
            .then(ok => {
                let n = viewHolder.getAdapterPosition();
                ui.todoList.getAdapter().notifyItemChanged(n);
                if (ok) {
                    ui.post(() => {
                        storages.create("wordbook45qq_wordList_" + todoList[n].sdcard).clear();
                        todoList.splice(n, 1);
                    });
                }
            });
    },
    clearView: function(recyclerView, viewHolder) {
        start = true;
        let x = move.x,
            y = move.y,
            z;
        if (x < y)
            for (; x < y; x++) {
                z = x + 1;
                [todoList[x], todoList[z]] = [todoList[z], todoList[x]];
            }
        else
            for (; y < x; x--) {
                z = x - 1;
                [todoList[x], todoList[z]] = [todoList[z], todoList[x]];
            }
        move = {};

        let view = ui.todoList.getLayoutManager().findViewByPosition(viewHolder.getAdapterPosition());
        if (view != null)
            view.setTranslationZ(0);
    }
})).attachToRecyclerView(ui.todoList);

ui.todoList.on("item_bind", function(itemView, itemHolder) {
    //跳转工作区监听
    itemView.item.on("click", () => {
        let con = files.read("./wordList.js") + "enter('" + itemHolder.item.title + "','" + itemHolder.item.sdcard + "');";

        engines.execScript("wordList_ui", java.lang.String.format('"ui";\n%s\nenter("%s", "%s")', require("./wordList.js"), itemHolder.item.title, itemHolder.item.sdcard));
    });

    //重新编辑监听
    itemView.edit.on("click", (view) => {
        let editDialog = dialogs.build({
            title: itemHolder.item.title,
            titleColor: themeJs.text,
            items: ["编辑", "导入文本", "格式化"],
            itemsColor: themeJs.text2,
            itemsSelectMode: "select",
        }).on("item_select", (index, item) => {
            switch (item) {
                case "编辑":
                    rewriteWorkJs.show(itemHolder.item.title, itemHolder.item.summary, function(title, summary) {
                        todoList[itemHolder.getPosition()].title = title;
                        todoList[itemHolder.getPosition()].summary = summary;

                        let view = ui.todoList.getLayoutManager().findViewByPosition(itemHolder.getPosition());
                        if (view != null)
                            ui.post(() => {
                                view.title.setText(title);
                                view.summary.setText(summary);
                            });
                    })
                    break;
                case "导入文本":
                    inAndOutJs.inTextToWork(itemHolder.item.sdcard);
                    break;
                case "格式化":
                    let deleteDialog = dialogs.build({
                        title: "确定要格式化「" + itemHolder.item.title + "」吗？",
                        titleColor: themeJs.text,
                        content: "将清空该单词本所有单词",
                        contentColor: themeJs.text2,
                        positive: "确定",
                        negative: "取消",
                    }).on("positive", () => {
                        ui.post(() => {
                            storages.create("wordbook45qq_wordList_" + itemHolder.item.sdcard).clear();
                            toast("已格式化！");
                        });
                    });
                    deleteDialog.getView().attr("bg", themeJs.layout);
                    deleteDialog.show();
                    break;
            }
        });

        editDialog.getView().attr("bg", themeJs.layout);
        editDialog.show();
    });
});

//创造右上角菜单
ui.emitter.on("create_options_menu", menu => {
    menu.add("格式化");
    menu.add("关于");
    menu.add("设置");
    menu.add("打赏作者💰");
});

//监听选项菜单点击
ui.emitter.on("options_item_selected", (e, item) => {
    switch (item.getTitle()) {
        case "格式化":
            let deleteDialog = dialogs.build({
                title: "确定要格式化吗？",
                titleColor: themeJs.text,
                content: "即将清空所有单词本及其单词",
                contentColor: themeJs.text2,
                positive: "确定",
                negative: "取消",
            }).on("positive", () => {
                for (let i = 0, n = todoList.length; i < n; i++) {
                    storages.create("wordbook45qq_wordList_" + todoList[i].sdcard).clear();
                }
                todoList.splice(0, todoList.length);
                toast("已格式化！");
            });
            deleteDialog.getView().attr("bg", themeJs.layout);
            deleteDialog.show();
            break;
        case "关于":
            let dialog = dialogs.build({
                title: "简单词本v" + app.versionName,
                titleColor: themeJs.text,
                content: "作者：四五qq\nQQ：2192003656\n微信：hazwbs",
                contentColor: themeJs.text2,
                positive: "返回",
            });
            dialog.getView().attr("bg", themeJs.layout);
            dialog.show();
            break;
        case "设置":
            settingJs.show();
            break;
        case "打赏作者💰":
            rewardJs.show();
    }
    e.consumed = true;
});

//加入按钮监听
ui.add.on("click", () => {
    var title;
    if (todoList.length < 1)
        title = "默认单词本";
    else {
        let name = "";
        for (let i = 1, isrename = false;; i++) {
            for (let j in todoList)
                if (todoList[j].title == "单词本" + i)
                    isrename = true;
            if (isrename)
                isrename = false;
            else {
                title = "单词本" + i;
                break;
            }
        }
    }
    addWorkJs.show(todoList, title, date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日 ", function(item, i) {
        ui.post(() => {
            ui.todoList.smoothScrollToPosition(i);
        }, 500);
    });
});

threads.start(function() {
    //该api只用于用户使用数据统计。
    http.get("http://simplewordbook.45qq.ltd/dailyactivityrecord.php");
});